<script setup>
import { defineProps, watch, ref, onMounted, onUnmounted, nextTick } from 'vue'
// import { ElButton, ElSwitch } from 'element-plus'


const props = defineProps({
    options: { type: Object, default: () => ({}) },
    apiData: { type: Object, default: () => ({}) },
    busStore: { type: Object, default: () => ({}) },
    privateStore: { type: Object, default: () => ({}) },
    ownStore: { type: Object, default: () => ({}) }
})

// 监听配置项变化
watch(() => props.options, (newValue, oldValue) => {
    console.log('配置项变化：', newValue, oldValue)
}, { deep: true })

// 监听接口数据变化
watch(() => props.apiData, (newValue, oldValue) => {
    console.log('接口数据变化：', newValue, oldValue)
}, { deep: true })

// 监听公用数据变化
watch(() => props.busStore, (newValue, oldValue) => {
    console.log('公用数据变化：', newValue, oldValue)
}, { deep: true })

// 监听私有数据变化
watch(() => props.privateStore, (newValue, oldValue) => {
    console.log('私有数据变化：', newValue, oldValue)
}, { deep: true })

const { $d3 } = getMDInstance()
const d3 = $d3


// 图表容器引用
const chartContainer = ref(null);

// 响应式数据
const chartData = ref([]);
const showPoints = ref(true);
const chartDimensions = ref({ width: 0, height: 0 });

// 图表相关变量
let svg, xScale, yScale, lineGenerator, tooltip;
const margin = { top: 20, right: 30, bottom: 30, left: 40 };

// 生成随机数据
const generateRandomData = () => {
    const newData = Array.from({ length: 20 }, (_, i) => ({
        date: new Date(2023, 0, i + 1),
        value: Math.floor(Math.random() * 100) + 10
    }));
    chartData.value = newData;
};

// 初始化图表
const initChart = () => {
    // 清除现有内容
    d3.select(chartContainer.value).selectAll('*').remove();

    // 设置尺寸
    const container = d3.select(chartContainer.value);
    chartDimensions.value.width = container.node().clientWidth;
    chartDimensions.value.height = 400;

    const innerWidth = chartDimensions.value.width - margin.left - margin.right;
    const innerHeight = chartDimensions.value.height - margin.top - margin.bottom;

    // 创建SVG
    svg = container.append('svg')
        .attr('width', chartDimensions.value.width)
        .attr('height', chartDimensions.value.height)
        .append('g')
        .attr('transform', `translate(${margin.left}, ${margin.top})`);

    // 创建比例尺
    xScale = d3.scaleTime()
        .range([0, innerWidth]);

    yScale = d3.scaleLinear()
        .range([innerHeight, 0]);

    // 创建线生成器
    lineGenerator = d3.line()
        .x(d => xScale(d.date))
        .y(d => yScale(d.value))
        .curve(d3.curveMonotoneX);

    // 创建坐标轴
    svg.append('g')
        .attr('class', 'x-axis')
        .attr('transform', `translate(0, ${innerHeight})`);

    svg.append('g')
        .attr('class', 'y-axis');

    // 创建tooltip
    tooltip = d3.select(chartContainer.value)
        .append('div')
        .attr('class', 'tooltip')
        .style('opacity', 0);

    // 绘制图表
    updateChart();
};

// 更新图表数据和显示
const updateChart = () => {
    if (!svg || chartData.value.length === 0) return;

    const innerWidth = chartDimensions.value.width - margin.left - margin.right;
    const innerHeight = chartDimensions.value.height - margin.top - margin.bottom;

    // 更新比例尺定义域
    xScale.domain(d3.extent(chartData.value, d => d.date));
    yScale.domain([0, d3.max(chartData.value, d => d.value)]);

    // 更新坐标轴
    svg.select('.x-axis')
        .call(d3.axisBottom(xScale).ticks(5));

    svg.select('.y-axis')
        .call(d3.axisLeft(yScale).ticks(5));

    // 更新线
    const line = svg.selectAll('.data-line')
        .data([chartData.value]);

    line.enter()
        .append('path')
        .attr('class', 'data-line')
        .merge(line)
        .transition()
        .duration(750)
        .attr('d', lineGenerator)
        .attr('fill', 'none')
        .attr('stroke', '#3b82f6')
        .attr('stroke-width', 2);

    // 更新数据点
    const points = svg.selectAll('.data-point')
        .data(chartData.value);

    // 移除不需要的点
    points.exit().remove();

    // 添加新点并更新现有点
    const newPoints = points.enter()
        .append('circle')
        .attr('class', 'data-point')
        .on('mouseover', handleMouseOver)
        .on('mouseout', handleMouseOut);

    // 合并并设置属性
    newPoints.merge(points)
        .transition()
        .duration(750)
        .attr('cx', d => xScale(d.date))
        .attr('cy', d => yScale(d.value))
        .attr('r', showPoints.value ? 4 : 0)
        .attr('fill', '#3b82f6');
};

// 鼠标悬停事件
const handleMouseOver = (event, d) => {
    tooltip.transition()
        .duration(200)
        .style('opacity', .9);

    tooltip.html(`
    <div class="tooltip-date">${d3.format('%Y-%m-%d')(d.date)}</div>
    <div class="tooltip-value">值: ${d.value}</div>
  `)
        .style('left', (event.pageX + 10) + 'px')
        .style('top', (event.pageY - 28) + 'px');
};

// 鼠标离开事件
const handleMouseOut = () => {
    tooltip.transition()
        .duration(500)
        .style('opacity', 0);
};

// 窗口大小变化时重绘图表
const handleResize = () => {
    if (chartContainer.value) {
        initChart();
    }
};

// 监听数据变化
watch(chartData, updateChart, { deep: true });
watch(showPoints, updateChart);

// 组件挂载时初始化
onMounted(() => {
    generateRandomData();
    nextTick(() => {
        initChart();
    });
    window.addEventListener('resize', handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
});
const value = ref(false)
</script>

<template>
    <div class="part-attr">
        <div :style="{ width: options.width, height: options.height, backgroundColor: options.backgroundColor }">
            <div class="chart-controls">
                <button @click="generateRandomData">生成随机数据</button>
                <label>
                    <input type="checkbox" v-model="showPoints" @change="updateChart" />
                    显示数据点
                </label>
            </div>
            <div ref="chartContainer" class="chart-area"></div>
        </div>
    </div>
</template>

<style scoped lang="scss">

.d3-chart-container {
    width: 100%;
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
}

.chart-controls {
    margin-bottom: 15px;
    display: flex;
    gap: 15px;
    align-items: center;
}

button {
    padding: 6px 12px;
    background-color: #3b82f6;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #2563eb;
}

.chart-area {
    width: 100%;
    height: 400px;
    border: 1px solid #e5e7eb;
    border-radius: 4px;
    overflow: hidden;
}

.data-line {
    transition: all 0.3s ease;
}

.data-point {
    transition: all 0.3s ease;
    cursor: pointer;
}

.data-point:hover {
    fill: #1d4ed8;
    r: 6;
}

.tooltip {
    position: absolute;
    padding: 8px 12px;
    background: rgba(0, 0, 0, 0.8);
    color: #fff;
    border-radius: 4px;
    pointer-events: none;
    font-size: 12px;
    transition: opacity 0.3s;
}

.tooltip-date {
    font-weight: bold;
    margin-bottom: 4px;
}
</style>